package com.atguigu.realtime.util;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.annotation.NoSink;
import com.atguigu.realtime.bean.TableProcess;
import com.atguigu.realtime.sink.PhoenixSink;
import lombok.SneakyThrows;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer;
import org.apache.flink.streaming.connectors.kafka.KafkaSerializationSchema;
import org.apache.kafka.clients.producer.ProducerRecord;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/23 10:28
 */
public class FlinkSinkUtil {
    public static SinkFunction<String> getKafkaSink(String topic) {
        
        Properties props = new Properties();
        props.put("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092");
        props.put("transaction.timeout.ms", 15 * 60 * 1000);
        
        return new FlinkKafkaProducer<String>(
            "default",
            new KafkaSerializationSchema<String>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(String element,
                                                                @Nullable Long timestamp) {
                    return new ProducerRecord<>(topic, element.getBytes(StandardCharsets.UTF_8));
                }
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
    }
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getKafkaSink() {
        Properties props = new Properties();
        props.put("bootstrap.servers", "hadoop162:9092,hadoop163:9092,hadoop164:9092");
        props.put("transaction.timeout.ms", 15 * 60 * 1000);
        
        return new FlinkKafkaProducer<Tuple2<JSONObject, TableProcess>>(
            "default",
            new KafkaSerializationSchema<Tuple2<JSONObject, TableProcess>>() {
                @Override
                public ProducerRecord<byte[], byte[]> serialize(Tuple2<JSONObject, TableProcess> element,
                                                                @Nullable Long timestamp) {
                    JSONObject data = element.f0;
                    TableProcess tp = element.f1;
                    return new ProducerRecord<>(tp.getSink_table(), data.toJSONString().getBytes(StandardCharsets.UTF_8));
                }
            },
            props,
            FlinkKafkaProducer.Semantic.EXACTLY_ONCE
        );
    }
    
    public static SinkFunction<Tuple2<JSONObject, TableProcess>> getPhoenixSink() {
        return new PhoenixSink();
    }
    
    public static <T> SinkFunction<T> getClickHouseSink(String db, String table, Class<T> tClass) {
        // 基于jdbc sink 封装ClickHouseSink
        String driver = "ru.yandex.clickhouse.ClickHouseDriver";
        String url = "jdbc:clickhouse://hadoop162:8123/" + db;
        
        Field[] fields = tClass.getDeclaredFields();
        // 拼接属性名
        String cs = "";
        String wh = "";
        for (Field field : fields) {
            // 如果这个field有NoSink 这个注解, 则不要拼接到sql中
            NoSink noSink = field.getAnnotation(NoSink.class);
            if (noSink == null) {
                cs += field.getName() + ",";
                wh += "?,";
            }
        }
        
        // insert into t(id, name, age)values(?,?,?)
        StringBuilder sql = new StringBuilder();
        sql
            .append("insert into ")
            .append(table)
            .append("(")
            // 拼接字段
            .append(cs, 0, cs.length() - 1)
            .append(")values(")
            // 拼接占位符
            .append(wh, 0, wh.length() - 1)
            .append(")");
        System.out.println(sql.toString());
        
        return getJdbcSink(driver, url, sql.toString());
    }
    
    public static <T> SinkFunction<T> getJdbcSink(String driver,
                                                  String url,
                                                  String sql) {
        return JdbcSink.sink(
            sql,
            new JdbcStatementBuilder<T>() {
                @SneakyThrows
                @Override
                public void accept(PreparedStatement ps,
                                   T t) throws SQLException {
                    // TODO 给sql中的站位符进行赋值. 根据sql语句来实现
                    // 获取class的3种方式:  Class.forName(...)  类名.class  对象.getClass
                    Field[] fields = t.getClass().getDeclaredFields();
                    
                    for (int i = 0, position = 1; i < fields.length; i++) {
                        Field field = fields[i];
                        NoSink noSink = field.getAnnotation(NoSink.class);
                        if (noSink == null) {
                            
                            field.setAccessible(true);
                            Object value = field.get(t);
                            ps.setObject(position++, value);
                        }
                    }
                }
            },
            new JdbcExecutionOptions.Builder()
                .withBatchIntervalMs(1000)
                .withBatchSize(1000)
                .withMaxRetries(3)
                .build(),
            new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                .withDriverName(driver)
                .withUrl(url)
                .build()
        );
    }
}
